package top.yehot.cmmu.spring.utils;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring工具类
 * 
 * @author lquan
 * @date 2022年4月2日 下午4:30:56
 */
@Component(value = "springUtilCustomize")
public final class SpringUtil implements ApplicationContextAware {

	@Getter
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringUtil.applicationContext == null) {
			SpringUtil.applicationContext = applicationContext;
		}
	}

	public static <T> T getBean(Class<T> clazz) {
		return SpringUtil.applicationContext.getBean(clazz);
	}

	public static Object getBean(String name) {
		return SpringUtil.applicationContext.getBean(name);
	}

	public static String getProperty(String key) {
		return SpringUtil.applicationContext.getEnvironment().getProperty(key);
	}

	/**
	 * 通过name,以及Clazz返回指定的Bean
	 *
	 * @param name  Bean名称
	 * @param clazz bean类型
	 * @param <T>   bean类型
	 * @return Bean对象
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return applicationContext.getBean(name, clazz);
	}
}